package com.ktmall.service.impl;

import com.ktmall.mapper.*;
import com.ktmall.pojo.*;
import com.ktmall.service.CartItemService;
import com.ktmall.vo.CartItemVo;
import com.ktmall.vo.PreOrder;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车相关Service实现类
 */
@Service
public class CartItemServiceImpl implements CartItemService {
    @Autowired
    private CartItemMapper cartItemMapper;

    @Autowired
    private SkuItemMapper skuItemMapper;
    @Autowired
    private GoodsItemMapper goodsItemMapper;
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private AttrItemMapper attrItemMapper;
    @Autowired
    private AttrValuesMapper attrValuesMapper;
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public int insert(CartItem cartItem) {
        CartItem cart = cartItemMapper.findByUserIdAndSkuId(cartItem.getUserId(),cartItem.getSkuId());
        if(cart != null){
            return cartItemMapper.updateBuyNum(cartItem.getUserId(),cartItem.getSkuId(),cartItem.getGoodsCount());
        }
        return cartItemMapper.insert(cartItem);
    }

    @Override
    public List<CartItem> findByUserId(Integer userId) {
        List<CartItem> list = cartItemMapper.findByUserId(userId);
        List<CartItem> cartGoodsList = list.stream().map((cart) -> {

            //2.通过购物车中的skuId查询商品SKU信息
            SkuItem sku = skuItemMapper.findById(cart.getSkuId());
            //3.查看SKU的属性值列表
            List<AttrValues> skuAttrVals = attrValuesMapper.getSkuAttrVals(sku.getStockSku());
            //4.查询每个SKU的属性列表
            List<AttrItem> attrs = attrItemMapper.findAttrByStockSku(sku.getStockSku());
            //5.遍历SKU的规格属性列表，查询出每个属性下的属性值列表
            attrs = attrs.stream().map(attr -> {
                //5.1查询出当前属性下的属性值列表
                List<AttrValues> aVs = skuAttrVals.stream().filter(attrV -> {
                    return attrV.getAttrId() == attr.getId(); //过滤条件：属性值对象的属性id==属性对象的id
                }).collect(Collectors.toList());
                attr.setValues(aVs); //将过滤出来的属性值列表aVs赋值给attr属性对象的values
                return attr;
            }).collect(Collectors.toList());
            sku.setSpecs(attrs);    //将属性列表attrs赋值给skuitem对象的specs集合。此时的attrs中包含属性值列表

            //6.查询次SKU所关联的商品
            GoodsItem goods = goodsItemMapper.findById(sku.getGoodsId());
            sku.setGoods(goods);    //赋值给goods商品对象给SkuItem
            cart.setSkuItem(sku);  //将赋值对象赋值给购物车对象
            //7.查询微信用户对象
            WxUser wxUser = wxUserMapper.findById(cart.getUserId());
            cart.setWxUser(wxUser);
            return cart;
        }).collect(Collectors.toList());
        return cartGoodsList;
    }

    @Override
    public int batchDel(Integer[] ids) {
        return cartItemMapper.batchDel(ids);
    }

    @Override
    public int update(Integer id, Integer goodsCount) {
        return cartItemMapper.update(id,goodsCount);
    }

    @Override
    public int updateSelected(Integer id, Integer selected) {
        return cartItemMapper.updateSelected(id,selected);
    }

    @Override
    public int updateAllSelected(Integer userId, Integer allSelected) {
        return cartItemMapper.updateAllSelected(userId,allSelected);
    }

    @Override
    public PreOrder getPreOrder(Integer userId) {
        // 获取默认地址
        AddressParams defaultAddress = addressMapper.getDefaultAddress(userId);
        // 获取选中的购物车商品
        List<CartItem> cartItemList = cartItemMapper.findSelectedByUserId(userId);

        if (cartItemList != null && !cartItemList.isEmpty()) {
            // 转换购物车商品为 CartItemVo 列表
            List<CartItemVo> vos = cartItemList.stream().map(cartItem -> {
                SkuItem skuItem = skuItemMapper.findById(cartItem.getSkuId());
                GoodsItem goodsItem = goodsItemMapper.findById(skuItem.getGoodsId());
                // 获取商品规格属性值
                List<AttrValues> skuAttrVals = attrValuesMapper.getSkuAttrVals(skuItem.getStockSku());
                // 获取商品规格属性列表
                List<AttrItem> attrs = attrItemMapper.findAttrByStockSku(skuItem.getStockSku());
                //查询每个SKU的属性下的属性值列表
                attrs = attrs.stream().peek(attr -> {
                    //5.1查询出当前属性下的属性值列表
                    List<AttrValues> aVs = skuAttrVals.stream().filter(attrV -> {
                        return attrV.getAttrId().equals(attr.getId()); //过滤条件：属性值对象的属性id==属性对象的id
                    }).collect(Collectors.toList());
                    attr.setValues(aVs); //将过滤出来的属性值列表aVs赋值给attr属性对象的values
                }).toList();
                skuItem.setSpecs(attrs);    //将属性列表attrs赋值给skuItem对象的specs集合。此时的attrs中包含属性值列表

                // 拼接商品规格属性值
                String attrsText = skuItem.getSpecs().stream()
                        .flatMap(spec -> spec.getValues().stream())
                        .map(AttrValues::getName)
                        .collect(Collectors.joining(" "));

                return new CartItemVo(
                        cartItem.getId(),
                        goodsItem.getId(),
                        skuItem.getId(),
                        goodsItem.getGoodsName(),
                        skuItem.getPicture(),
                        cartItem.getGoodsCount(),
                        skuItem.getPrice(),
                        skuItem.getPrice().multiply(new BigDecimal("0.9")).setScale(2),
                        Integer.valueOf(skuItem.getInventory()+""),
                        cartItem.getSelected() == 1,
                        attrsText
                );
            }).toList();

            return new PreOrder(defaultAddress, vos);
        }
        return null;
    }
}
